<template>
  <div>
    <el-row :gutter="30">
      <el-col v-bind="grid">
        <div class="Nav">
          <div class="input">
            <el-input
              v-model="filterText"
              placeholder="选择分类"
              prefix-icon="el-icon-search"
              style="width: 100%"
              clearable
            />
          </div>
          <div class="trees-coadd">
            <div class="scollhide">
              <div
                class="trees"
                :style="{ maxHeight: !pictureType ? '345px' : '700px' }"
              >
                <el-tree
                  ref="tree"
                  :data="treeData2"
                  :filter-node-method="filterNode"
                  :props="defaultProps"
                  highlight-current
                >
                  <div
                    slot-scope="{ node, data }"
                    class="custom-tree-node"
                    @click.stop="handleNodeClick(data)"
                  >
                    <div>
                      <span
                        class="custom-tree-node-label"
                        :class="{
                          'custom-tree-node-label-color':
                            data.id === tableData.pid,
                        }"
                        :title="node.label"
                        >{{ node.label }}</span
                      >
                      <span
                        v-if="data.space_property_name"
                        style="font-size: 11px; color: #3889b1"
                        >（{{ data.name }}）</span
                      >
                    </div>
                    <span class="el-ic">
                      <el-dropdown>
                        <span class="el-dropdown-link">
                          <i class="el-icon-more" />
                        </span>
                        <el-dropdown-menu slot="dropdown">
                          <el-dropdown-item
                            v-if="data.pId === 0"
                            @click.native.stop="onAdd(data.id)"
                            >添加分类</el-dropdown-item
                          >
                          <el-dropdown-item
                            v-if="node.label !== '全部图片'"
                            @click.native="onEdit(data)"
                            >编辑分类</el-dropdown-item
                          >
                          <el-dropdown-item
                            v-if="node.label !== '全部图片'"
                            @click.native="handleDelete(data.id)"
                            >删除分类</el-dropdown-item
                          >
                        </el-dropdown-menu>
                      </el-dropdown>
                    </span>
                  </div>
                </el-tree>
              </div>
            </div>
          </div>
        </div>
      </el-col>
      <el-col v-bind="grid2" class="colLeft">
        <div class="conter mb15">
          <div class="bnt">
            <el-button
              v-if="!pictureType"
              size="small"
              type="primary"
              class="btn-mb"
              @click="checkPics"
              >使用选中图片</el-button
            >
            <div class="mr20 mb20">
              <el-button-group>
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="上传图片"
                  placement="top-start"
                >
                  <el-upload
                    class="upload-demo"
                    action
                    :http-request="handleUploadForm"
                    :before-upload="beforeExcelUpload"
                    :headers="myHeaders"
                    :show-file-list="false"
                    multiple
                  >
                    <el-button
                      icon="el-icon-upload2"
                      size="mini"
                      style="font-size: 15px"
                    />
                  </el-upload>
                </el-tooltip>
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="添加分类"
                  placement="top-start"
                >
                  <el-button
                    icon="el-icon-circle-plus-outline"
                    style="font-size: 15px"
                    size="mini"
                    @click="onAdd(10000)"
                  />
                </el-tooltip>
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="删除图片"
                  placement="top-start"
                >
                  <el-button
                    icon="el-icon-delete"
                    style="font-size: 15px"
                    size="mini"
                    @click.stop="editPicList('图片')"
                  />
                </el-tooltip>
              </el-button-group>
            </div>
            <el-select
              v-model="sleOptions.attachment_category_name"
              placeholder="图片移动至"
              class="mb20"
              size="small"
            >
              <el-option
                class="demo"
                :label="sleOptions.attachment_category_name"
                :value="sleOptions.attachment_category_id"
                style="
                  max-width: 560px;
                  height: 200px;
                  overflow: auto;
                  background-color: #fff;
                "
              >
                <el-tree
                  ref="tree2"
                  :data="treeData2"
                  :filter-node-method="filterNode"
                  :props="defaultProps"
                  highlight-current
                  @node-click="handleSelClick"
                />
              </el-option>
            </el-select>
          </div>
          <div v-loading="loadingPic" class="pictrueList acea-row">
            <div v-show="isShowPic" class="imagesNo">
              <i
                class="el-icon-picture"
                style="font-size: 60px; color: rgb(219, 219, 219)"
              />
              <span class="imagesNo_sp">图片库为空</span>
            </div>
            <div
              class="conters scrollbarAll"
              :style="{ maxHeight: !pictureType ? '296px' : '700px' }"
            >
              <div
                v-for="(item, index) in pictrueList.list"
                :key="index"
                class="gridPic"
              >
                <img
                  v-lazy="$uploadURL(item.path)"
                  :class="item.isSelect ? 'on' : ''"
                  @click="changImage(item, index, pictrueList.list)"
                />
              </div>
            </div>
          </div>
        </div>
        <div class="block el-block">
          <el-pagination
            :page-sizes="!pictureType ? [10, 20, 30, 40] : [30, 60, 90, 120]"
            :page-size="tableData.limit"
            :current-page.sync="tableData.page"
            :pager-count="5"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pictrueList.total"
            @size-change="handleSizeChange"
            @current-change="pageChange"
          />
        </div>
      </el-col>
    </el-row>
    <el-dialog
      :title="bizTitle"
      :visible.sync="visible"
      destroy-on-close
      :close-on-click-modal="false"
      :modal="modals"
      @close="closeModel"
    >
      <el-form
        v-if="visible"
        ref="editPram"
        v-loading="loading"
        :model="editPram"
        label-width="100px"
      >
        <el-form-item
          label="上级分类"
          prop="pid"
          :rules="[
            {
              type: 'number',
              required: true,
              message: '请选择上级分类',
              trigger: ['blur', 'change'],
            },
          ]"
        >
          <!--          <el-cascader v-model="editPram.pid" :options="treeData2" :props="categoryProps" style="width:100%" />-->
          <el-select
            v-model="editPram.pid"
            placeholder="请选择上级分类"
            style="width: 100%"
          >
            <el-option
              v-for="item in treeData2"
              :key="item.value"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="分类名称"
          prop="name"
          :rules="[
            {
              required: true,
              message: '请输入分类名称',
              trigger: ['blur', 'change'],
            },
          ]"
        >
          <el-input v-model="editPram.name" placeholder="分类名称" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="editPram.sort" :min="0" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handlerSubmit('editPram')"
            >确定</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { fileImageApi } from "@/api/oss";
import { mapState, mapActions, mapMutations,mapGetters } from "vuex";
import {
  GETAttachmentCatesListAPi,
  GETAttachmentsListAPi,
  POSTAttachmentCatesApi,
  PUTAttachmentCatesApi,
  DELAttachmentCatesApi,
  DELAttachmentsApi,
  PATCHAttachmentsApi,
} from "@/api/setting";
import { getToken,getRouteId } from "@/utils/auth";

export default {
  name: "Upload",
  props: {
    pictureType: {
      type: String,
      default: "",
    },
    isMore: {
      type: String,
      default: "1",
    },
    modelName: {
      type: String,
      default: "",
    },
    checkedMore: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      loadingPic: false,
      loading: false,
      modals: false,
      allTreeList: [],
      editPram: {
        pid: 1000,
        name: "",
        type: 2,
        sort: 1,
        status: 0,
        url: "url",
        id: 0,
      },
      visible: false,
      bizTitle: "",
      sleOptions: {
        cateId: "",
      },
      list: [],
      grid: {
        xl: 7,
        lg: 7,
        md: 7,
        sm: 7,
        xs: 24,
      },
      grid2: {
        xl: 17,
        lg: 17,
        md: 17,
        sm: 17,
        xs: 24,
      },
      filterText: "",
      treeData: [],
      treeData2: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
      tableData: {
        page: 1,
        limit: 10,
        pid: -1,
      },
      classifyId: 0,
      myHeaders: { "X-Token": getToken() },
      treeFrom: {
        status: -1,
        type: 2,
      },
      pictrueList: {
        list: [],
        total: 0,
      },
      isShowPic: false,
      checkPicList: [],
      ids: [],
      listPram: {
        pid: 0,
        type: 2,
        status: 0,
        name: "",
        page: 1,
        limit: 9999,
      },
      localImg: "",
    };
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
  },
  computed: {
    selectedId(){
        return getRouteId()
    }
    
  },
  mounted() {
    console.log("Selected ID>>>>>>>>>>:", this.selectedId);
    this.pictureType
      ? (this.tableData.limit = 30)
      : (this.tableData.limit = 10);
    if (this.$route && this.$route.query.field === "dialog")
      import("../../../public/UEditor/dialogs/internal.js");
    this.getList();
    this.getFileList();
  },
  methods: {
    closeModel() {
      this.$refs["editPram"].resetFields();
    },
    getSelectedId() {
    return this.selectedId;  // 访问映射的 getter 数据
  },
    handlerSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.editPram.pid === 10000) this.editPram.pid = 0;

          if (this.bizTitle === "添加分类") {
            POSTAttachmentCatesApi(this.selectedId,{
              name: this.editPram.name,
              pid: this.editPram.pid,
              sort: this.editPram.sort,
            }).then(() => {
              this.$message.success("创建成功");
              this.visible = false;
              this.getList();
            });
          } else if (this.bizTitle === "编辑分类") {
            PUTAttachmentCatesApi(this.selectedId,this.editPram.id, {
              name: this.editPram.name,
              pid: this.editPram.pid,
              sort: this.editPram.sort,
            }).then(() => {
              this.$message.success("编辑成功");
              this.visible = false;
              this.getList();
            });
          }
        } else {
          return false;
        }
      });
    },
    // 搜索分类
    filterNode(value, data) {
      if (!value) return true;
      return data.name && data.name.indexOf(value) !== -1;
    },
    // 所有分类
    getList() {
      GETAttachmentCatesListAPi(this.selectedId).then((res) => {
        this.treeData = res;
        this.treeData.unshift({ name: "全部图片", id: 10000, pId: 0 });
        this.treeData2 = [...this.treeData];
      });
    },
    // 添加分类
    onAdd(id) {
      this.tableData.pid = id;
      if (this.tableData.pid === 10000) this.tableData.pid = -1;
      this.bizTitle = "添加分类";
      this.visible = true;
      if (id) {
        this.editPram.pid = id;
        this.editPram.sort = 1;
        this.editPram.name = "";
      }
    },
    // 编辑
    onEdit(data) {
      if (data["id"] === 10000) data["id"] = 0;
      this.bizTitle = "编辑分类";
      this.visible = true;
      if (data["id"]) {
        this.editPram.id = data["id"];
        this.editPram.pid = data["pId"] === 0 ? 10000 : data["pId"];
        this.editPram.sort = data["sort"];
        this.editPram.name = data["name"];
      }
    },
    // 删除
    handleDelete(id) {
      if (id === 10000) id = 0;
      this.$modalSure().then(() => {
        console.log(this.selectedId,"***",id);
        DELAttachmentCatesApi(this.selectedId,id).then(() => {
          this.$message.success("删除成功");
          this.getList();
        });
      });
    },
    handleNodeClick(data) {
      if (this.tableData.pid === data.id) return;
      this.tableData.page = 0;
      this.tableData.pid = data.id;
      this.getFileList();
    },
    // 文件上传之前的钩子
    beforeExcelUpload(file) {
      const isSize = file.size / 1024 / 1024 < 2;
      const isExcel =
        file.name.split(".")[1] === "jpg" ||
        file.name.split(".")[1] === "png" ||
        file.name.split(".")[1] === "gif";
      if (!isSize) {
        this.$message({
          message: "上传文件大小不能超过 2MB!",
          type: "warning",
        });
        return false;
      }
      if (!isExcel) {
        this.$message({
          message: "请上传jpg、png、gif格式的图片!",
          type: "warning",
        });
        return false;
      }
      return isSize && isExcel;
    },
    // 上传
    handleUploadForm(param) {
      console.log("File", param);
      const formData = new FormData();
      formData.append("File", param.file);
      console.log("File", param.file);
      formData.append(
        "CateId",
        this.tableData.pid === -1 ? 0 : this.tableData.pid
      );
      formData.append("Type", 0);
      const loading = this.$loading({
        lock: true,
        text: "上传中，请稍候...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      fileImageApi(this.selectedId,formData)
        .then(() => {
          loading.close();
          this.$message.success("上传成功");
          this.getFileList();
        })
        .catch(() => {
          loading.close();
        });
    },
    // 文件列表
    getFileList() {
      if (this.tableData.pid === 10000) this.tableData.pid = -1;
      this.$set(this, "loadingPic", true);
      GETAttachmentsListAPi(this.selectedId,{
        // pageNumber: this.tableData.page,
        // pageSize: this.tableData.limit,
        // cateId: this.tableData.pid,
        cateId:this.tableData.pid,
        orderby:'id desc'
      })
        .then(async (res) => {
          this.$set(this.pictrueList, "list", res.data);
          if (this.tableData.page === 1 && this.pictrueList.list.length > 0)
            this.pictrueList.list[0].localImg = this.localImg;
          this.pictrueList.total = res.head.totalCount;
          this.$set(this, "loadingPic", false);
          this.$set(this, "isShowPic", false);
        })
        .catch((err) => {
          this.$set(this, "loadingPic", false);
          this.$set(this, "isShowPic", true);
          this.pictrueList.list = [];
          this.pictrueList.total = 0;
        });
    },
    pageChange(page) {
      this.tableData.page = page;
      this.getFileList();
    },
    handleSizeChange(val) {
      this.tableData.limit = val;
      this.getFileList();
    },
    // 选中图片
    changImage(item, index, row) {
      let selectItem = "";
      this.$set(
        item,
        "isSelect",
        item.isSelect === undefined ? true : !item.isSelect
      );
      selectItem = this.pictrueList.list.filter((item) => {
        return item.isSelect === true;
      });
      this.checkPicList = selectItem;
      this.ids = [];
      this.checkPicList.map((item, index) => {
        this.ids.push(item.id);
      });
    },
    // 点击使用选中图片
    checkPics() {
      if (!this.checkPicList.length)
        return this.$message.warning("请先选择图片");
      if (this.checkPicList.length !== 0 && this.isMore === "2") {
        this.$emit("getImage", [...this.checkedMore, ...this.checkPicList]);
      } else if (
        this.$route &&
        this.$route.query.field === "dialog" &&
        this.$route.query.type === "2"
      ) {
        let str = "";
        for (let i = 0; i < this.checkPicList.length; i++) {
          str +=
            '<img src="' + this.$uploadURL(this.checkPicList[i].path) + '">';
        }
        // eslint-disable-next-line no-undef
        nowEditor.dialog.close(true);
        // eslint-disable-next-line no-undef
        nowEditor.editor.setContent(str, true);
      } else {
        if (this.isMore === "1" && this.checkPicList.length > 1)
          return this.$message.warning("最多只能选一张图片");
        this.$emit("getImage", [...this.checkedMore, ...this.checkPicList]);
      }
    },
    // 删除图片
    editPicList(tit) {
      if (!this.checkPicList.length)
        return this.$message.warning("请先选择图片");
      this.$modalSure().then(() => {
        DELAttachmentsApi(this.selectedId,`(${this.ids.join(",")})`).then(() => {
          this.$message.success("刪除成功");
          this.getFileList();
          this.checkPicList = [];
        });
      });
    },
    // 移动分类点击
    handleSelClick(node) {
      if (this.ids.length) {
        this.$set(this, "sleOptions", { cateId: this.ids });
        this.getMove(this.sleOptions.cateId.join(","), [
          {
            op: "replace",
            path: "/cateId",
            value: node.id === 10000 ? 0 : node.id,
          },
        ]);
      } else {
        this.$message.warning("请先选择图片");
      }
    },
    getMove(cateId, patch) {
      console.log(this.selectedId,cateId, patch,"<<<");
      PATCHAttachmentsApi(this.selectedId,cateId, patch)
        .then(async (res) => {
          this.$message.success("操作成功");
          this.clearBoth();
          this.getFileList();
        })
        .catch((res) => {
          this.clearBoth();
        });
    },
    clearBoth() {
      this.$set(this, "sleOptions", { cateId: "" });
      this.$set(this, "checkPicList", []);
      this.$set(this, "ids", []);
    },
  },
};
</script>

<style scoped lang="scss">
.demo::-webkit-scrollbar {
  display: none; /* Chrome Safari */
}

.demo {
  scrollbar-width: none; /* firefox */
  -ms-overflow-style: none; /* IE 10+ */
  overflow-x: hidden;
  overflow-y: auto;
}
.temp {
  height: 0;
  margin-bottom: 0;
  border: none;
  padding: 0;
}
.selectTreeClass {
  background: #d5e8fc;
}
.treeBox {
  width: 100%;
  height: 100%;
}
.upload-demo {
  display: inline-block !important;
  float: left;
}
.tree_w {
  padding: 20px 30px;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 12px;
  padding-right: 8px;
  color: #4386c6;
}
.custom-tree-node-label {
  color: rgba(0, 0, 0, 0.6);
  display: block;
  width: 125px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  &.custom-tree-node-label-color {
    color: rgb(45, 140, 240) !important;
  }
}
.el-ic {
  display: none;
  i,
  span {
    /*padding: 0 14px;*/
    font-size: 18px;
    font-weight: 600;
  }
  .svg-icon {
    color: #4386c6;
  }
}
.el-tree-node__content {
  height: 38px;
}
.el-tree-node__expand-icon {
  color: #428bca !important;
  /*padding: 10px 10px 0px 10px !important;*/
}
.el-tree-node__content:hover .el-ic {
  color: #428bca !important;
  display: inline-block;
}
.el-tree-node__content:hover {
  font-weight: bold;
}
.el-tree--highlight-current
  .el-tree-node.is-current
  > .el-tree-node__content
  :hover {
  .el-tree-node__expand-icon.is-leaf {
    color: transparent;
    cursor: default;
  }
  /*background-color: #3998d9;*/
  .custom-tree-node {
    font-weight: bold;
  }
  .el-tree-node__expand-icon {
    font-weight: bold;
  }
}
.el-dialog__body {
  .upload-container .image-preview .image-preview-wrapper img {
    height: 100px;
  }
  .el-dialog .el-collapse-item__wrap {
    padding-top: 0px;
  }
  .spatial_img {
    .el-collapse-item__wrap {
      margin-bottom: 0;
      padding-top: 0px;
    }
  }
  .upload-container .image-preview .image-preview-wrapper {
    width: 120px;
  }
  .upload-container .image-preview .image-preview-action {
    line-height: 100px;
    height: 100px;
  }
}
.trees-coadd {
  width: 100%;
  border-radius: 4px;
  overflow: hidden;
  position: relative;
  .scollhide {
    overflow-x: hidden;
    overflow-y: scroll;
    padding: 10px 0 10px 0;
    box-sizing: border-box;
    .trees {
      width: 100%;
    }
  }
  .scollhide::-webkit-scrollbar {
    display: none;
  }
}
.conters {
  display: flex;
  flex-wrap: wrap;
  /*max-height: 296px;*/
  overflow: auto;
}
.conters:after {
  content: "";
  width: 410px !important;
}
.gridPic {
  margin-right: 15px;
  margin-bottom: 10px;
  width: 110px;
  height: 110px;
  cursor: pointer;
  img {
    width: 100%;
    height: 100%;
    display: block;
  }
}
.conter {
  width: 99%;
  height: 100%;
  .bnt {
    width: 100%;
    padding: 0 13px 10px 7px;
    box-sizing: border-box;
    display: flex;
    .btn-mb {
      margin-bottom: 20px !important;
      margin-right: 20px !important;
    }
  }
  .pictrueList {
    /*padding-left: 15px;*/
    width: 100%;
    el-image {
      width: 100%;
      border: 2px solid #fff;
    }
    .on {
      border: 2px solid #5fb878;
    }
  }
  .el-image {
    width: 110px;
    height: 110px;
    cursor: pointer;
  }
  .imagesNo {
    width: 100%;
    display: flex;
    justify-content: center;
    flex-direction: column;
    align-items: center;
    margin: 65px 0;
    .imagesNo_sp {
      font-size: 13px;
      color: #dbdbdb;
      line-height: 3;
    }
  }
}

::v-deep .el-block {
  display: flex;
  justify-content: flex-end;
}
</style>
